import
java.util.*;
public
class
CharacterOrder {
static
void
addEdge(ArrayList<Integer>[] adj,
char
u,
char
v) {
adj[u -
'a'
].add(v -
'a'
);
}
static
void
dfs(ArrayList<Integer>[] adj,
int
[] col,
int
curr,
boolean
[] isCyclic) {
col[curr] =
1
;
for
(
int
i =
0
; i < adj[curr].size(); i++) {
int
x = adj[curr].get(i);
if
(col[x] ==
1
) {
isCyclic[
0
] =
true
;
return
;
}
else
if
(col[x] ==
0
) {
dfs(adj, col, x, isCyclic);
}
}
col[curr] =
2
;
}
static
boolean
checkCycle(ArrayList<Integer>[] adj,
int
[] col,
int
k) {
boolean
[] isCyclic = {
false
};
for
(
int
i =
0
; i < k; i++) {
if
(col[i] ==
0
) {
dfs(adj, col, i, isCyclic);
}
}
return
isCyclic[
0
];
}
static
void
topologicalSortUtil(ArrayList<Integer>[] adj,
int
u,
boolean
[] visited, Stack<Integer> st) {
visited[u] =
true
;
for
(
int
i =
0
; i < adj[u].size(); i++) {
int
v = adj[u].get(i);
if
(!visited[v]) {
topologicalSortUtil(adj, v, visited, st);
}
}
st.push(u);
}
static
void
topologicalSort(ArrayList<Integer>[] adj,
int
V) {
boolean
[] visited =
new
boolean
[V];
Stack<Integer> st =
new
Stack<>();
for
(
int
i =
0
; i < V; i++) {
visited[i] =
false
;
}
for
(
int
i =
0
; i < V; i++) {
if
(!visited[i]) {
topologicalSortUtil(adj, i, visited, st);
}
}
while
(!st.isEmpty()) {
System.out.print((
char
) (st.pop() +
'a'
) +
" "
);
}
}
static
void
printOrder(String[] words,
int
n) {
int
[] frq =
new
int
[
26
];
int
k =
0
;
for
(
int
i =
0
; i < n; i++) {
String s = words[i];
for
(
int
j =
0
; j < s.length(); j++) {
frq[s.charAt(j) -
'a'
]++;
if
(frq[s.charAt(j) -
'a'
] ==
1
)
k++;
}
}
ArrayList<Integer>[] adj =
new
ArrayList[k];
for
(
int
i =
0
; i < k; i++) {
adj[i] =
new
ArrayList<>();
}
for
(
int
i =
0
; i < n -
1
; i++) {
String word1 = words[i];
String word2 = words[i +
1
];
int
j =
0
;
while
(j < word1.length() && j < word2.length()) {
if
(word1.charAt(j) != word2.charAt(j)) {
addEdge(adj, word1.charAt(j), word2.charAt(j));
break
;
}
j++;
}
}
int
[] col =
new
int
[k];
if
(checkCycle(adj, col, k)) {
System.out.println(
"Valid Order is not possible"
);
return
;
}
topologicalSort(adj, k);
}
public
static
void
main(String[] args) {
String[] words = {
"baa"
,
"abcd"
,
"abca"
,
"cab"
,
"cad"
};
int
n = words.length;
printOrder(words, n);
}
}